//
//  LauLabel.swift
//  textKit准备的工作
//
//  Created by Lausen on 2017/5/20.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit

/**
 1:使用textKit接管label底层的实现 -- 绘制textStroage的文本内容
 2:使用正则表达式过滤URL
 3:交互
 */
@objc protocol LauLabelSelectedDelegate: NSObjectProtocol {
    
    @objc optional func didSelectedUrlString(label: LauLabel, text: String)
}

class LauLabel: UILabel {

    /// 这个是代理属性
    weak var delegate: LauLabelSelectedDelegate?
    
    override var text: String?{
        
        didSet{
            
            //重新准备文本
            prepareTextContent()
        }
    }
    
    override var attributedText: NSAttributedString?{
        
        didSet{
            
            // 重新准备属性文本
            prepareTextContent()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareSystemText()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        prepareSystemText()
    }

    override func drawText(in rect: CGRect) {
        
        let range = NSRange(location: 0, length: textStroage.length)
        
        layoutManager.drawBackground(forGlyphRange: range, at: CGPoint())
        
        layoutManager.drawGlyphs(forGlyphRange: range, at: CGPoint())
    }
    
    // MARK: -- 开始点击了屏幕上的文字
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        guard let location = touches.first?.location(in: self) else{
            
            return
        }
        
        let idx = layoutManager.glyphIndex(for: location, in: container)
        
        for r in urlRanges ?? [] {
            
            if NSLocationInRange(idx, r){
                
                textStroage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: r)
                
                //重新绘制
                setNeedsDisplay()
                
                let str = (textStroage.string as NSString).substring(with: r)
                
                delegate?.didSelectedUrlString!(label: self, text: str)
                
            }else{
                
                print("返回")
            }
        }
    }
    
    // MARK: -- 手指移开的方法
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        guard let location = touches.first?.location(in: self) else{
            
            return
        }
        
        let idx = layoutManager.glyphIndex(for: location, in: container)
        
        for r in urlRanges ?? [] {
            
            if !NSLocationInRange(idx, r) {
                
                textStroage.addAttributes([NSForegroundColorAttributeName: UIColor.red], range: r)
                
                setNeedsDisplay()
            }else{
                
                textStroage.addAttributes([NSForegroundColorAttributeName: UIColor.blue], range: r)
                
                setNeedsDisplay()
            }
        }
        
    }
    
    // MARK: -- 在这儿制定绘制的区域
    override func layoutSubviews() {
        super.layoutSubviews()
        
        ///设置文本管理的区域
        container.size = bounds.size
    }
    
    // MARK: -- textKit的核心对象
    /// 属性文本的属性
    fileprivate lazy var textStroage = NSTextStorage()
    /// 负责文本"字形"的布局
    fileprivate lazy var layoutManager = NSLayoutManager()
    /// 设定文本绘制的范围
    fileprivate lazy var container = NSTextContainer()
}

extension LauLabel{
    
    func prepareSystemText() {
    
        //0:先打开可交互
        isUserInteractionEnabled = true
        
        //1:管理文本内容
        prepareTextContent()
        
        //2:
        textStroage.addLayoutManager(layoutManager)
        layoutManager.addTextContainer(container)
    }
    
    func prepareTextContent() {
        
        if let attributedText = attributedText { // 如果属性的文本有值
            
            textStroage.setAttributedString(attributedText)
            
        }else if let text = text{ // 如果文本有值
            
            textStroage.setAttributedString(NSAttributedString(string: text))
            
        }else{ //如果属性文本和文本都没有值
            
            textStroage.setAttributedString(NSAttributedString(string: ""))
        }
        
        for r in urlRanges ?? [] {
            
            textStroage.addAttributes(
                [NSForegroundColorAttributeName: UIColor.red,
                 NSBackgroundColorAttributeName: UIColor.init(white: 0.9, alpha: 1.0)
                ],
                range: r)
        }
        
    }
}


// MARK: - 获取url的范围
extension LauLabel{
    
    var urlRanges: [NSRange]?{
        
        //1:设置匹配规则
        let patterns = ["[a-zA-Z]*://[a-zA-Z0-9/\\.]*","#.*?#","@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*"]
        
        /// 创建一个可变的数组
        var rangs = [NSRange]()
        
        for pattern in patterns {
            
            
            guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else{
                
                return nil
            }
            
            let matches = regx.matches(in: textStroage.string, options: [], range: NSRange(location: 0, length: textStroage.length))
            
            
            
            for m in matches {
                
                rangs.append(m.rangeAt(0))
            }
        }
        
        return rangs
    }
}








